package com.py.chat.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.google.protobuf.MessageLite;
import com.py.chat.UI.UI;
import com.py.chat.proto.ProtoMapper;
import com.py.chat.utils.PropertiesUtil;
import com.py.net.client.input.CmdRoute;
import com.py.net.client.input.IInputBuilder;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ChatClient {

	private static String HOST;
	private static int PORT;

	static {
		HOST = PropertiesUtil.getValue("host");
		PORT = Integer.parseInt(PropertiesUtil.getValue("port"));
		System.err.println(HOST+"-----"+PORT);
	}

	public static void chatClient() throws Exception {
    	ProtoMapper.init();
    	CmdRoute.init();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new ClientInitializer());
			// TODO Channel ChannelFuture 的区别
			Channel ch = b.connect(HOST, PORT).sync().channel();
			ChannelFuture lastWriteFuture = null;
			// 显示界面
//			UI.mainUI();
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			while (true) {
				UI.mainUI();
				String cmd = in.readLine().trim();
				//退出
				if("E".equals(cmd)){
					ch.close().sync();
					break;
				}
				MessageLite msg = buildMsg(in,cmd);
				if (msg != null) {
					ch.writeAndFlush(msg);
				}
				
				if (lastWriteFuture != null) {
	                lastWriteFuture.sync();
	            }
				Thread.sleep(1000);
			}
		} finally {
			group.shutdownGracefully();
		}
	}

	public static MessageLite buildMsg(BufferedReader in,String cmd) throws Exception{
		IInputBuilder inputBuilder = CmdRoute.getInputBuilder(cmd);
		MessageLite msg = null;
		if(inputBuilder != null){
			while(msg == null){
				if(inputBuilder.needParam()){
					inputBuilder.showUI();
					String line = in.readLine().trim();
					if(line.equals("Q")){
						return null;
					}
					msg = inputBuilder.builder(line);
				}else{
					msg = inputBuilder.builder();
				}
			}
		}else{
			UI.msgUI("输入命令无效");
		}
		return msg;
	}
	public static void main(String[] args) throws Exception {
		ChatClient.chatClient();
	}

}
